package com.baomihua.utils.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

/**
 * json转换工具类
 * @author mac
 */
public class JsonUtils {

    private final Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    /**
     * 定义jackson对象
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description:</p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data){
        try {
           String  string = MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json转化为对象
     * @param jsonData json数据
     * @param beanType 对象中的Object类型
     * @param <T>
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType){
        T t = null;
        try {
            t = MAPPER.readValue(jsonData, beanType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json数据转换成pojo对象List
     * <p>Title jsonToList</p>
     * <p>Description:</p>
     * @param jsonData
     * @param beanType
     * @param <T>
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType){
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            MAPPER.readValue(jsonData,javaType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
